package site.madai.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import site.madai.constant.MessageConstant;
import site.madai.entity.Result;
import site.madai.pojo.Setmeal;
import site.madai.service.SetmealService;
import site.madai.utils.SerializeUtil;

import java.util.List;

/**
 * @Project: site.madai.controller
 * @Author: ShaoDi Wang
 * @Date: Created in 2019-06-28 19:32
 * @Description:
 * @Version: 1.0
 */
@RestController
@RequestMapping("setmeal")
public class SetmealController {

    @Autowired
    JedisPool jedisPool;
    @Reference
    private SetmealService setmealService;

    @RequestMapping("getAllSetmeal")
    public Result getAllSetmeal() {
        byte[] bytes = jedisPool.getResource().get("mealList".getBytes());
        List setmeals = (List<Setmeal>) SerializeUtil.unserialize(bytes);
        if (setmeals == null) {
            try {
                List<Setmeal> setmealList = setmealService.getAllSetmeal();
                return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS,
                        setmealList);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.GET_SETMEAL_LIST_FAIL);
            }
        } else {
            return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS,
                    setmeals);
        }
    }

    @RequestMapping("findSetmealById")
    public Result findSetmealById(Integer id) {
        byte[] key = ("setmeal" + "-" + id.toString()).getBytes();
        byte[] bytes = jedisPool.getResource().get(key);
        Setmeal setmeal = (Setmeal) SerializeUtil.unserialize(bytes);
        System.out.println(setmeal);
        if (setmeal == null) {
            try {
                Setmeal setmealByIdformobile = setmealService.findSetmealByIdformobile(id);
                return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmealByIdformobile);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
            }
        } else {
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
        }
    }
}
